<script setup lang="ts">
  import { formData } from './index';
  import useLoading from '@/hooks/loading';
  import { forEach, throttle } from 'lodash-es';
  const { loadingIcon, setLoading } = useLoading();
  const submitData = ref<Namespace.areaTableType>();
  const myform = ref<any>(null);
  const formFieldset = ref<any>();
  const emit = defineEmits<Emits>();
  interface Emits {
    (e: 'update:value', val: boolean): void;
    (e: 'update:object', val: Namespace.areaTableType, title: string): void;
  }
  const props = defineProps({
    show: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
    data: {
      type: Object,
      default: () => {},
    },
  });
  watch(
    () => props,
    (value) => {
      if (value.data) {
        formFieldset.value = value.data;
      }
      forEach(formData.formRules, (item) => {
        for (let i = 0; i < item.length; i++) {
          if (item[i].field === 'regionType') {
            if (value.title == '编辑') {
              item[i] = {
                ...item[i],
                readonly: true,
              };
            } else {
              item[i] = {
                ...item[i],
                readonly: false,
              };
            }
          }
        }
      });
    },
    {
      deep: true,
    },
  );
  const handleClose = () => {
    emit('update:value', false);
    formData.formFields = {
      regionName: '',
      regionCode: '',
      regionType: 0,
      originId: 0,
    };
  };
  const hanldFromData = (value: Namespace.areaTableType) => {
    submitData.value = value;
  };
  const getForm = throttle(async () => {
    myform.value.validate();
    await setTimeout(async () => {
      setLoading(true);
      if (myform.value.success) {
        emit('update:object', submitData.value as Namespace.areaTableType, props.title);
        myform.value.reset();
      }
      setLoading(false);
    });
  });
  const reset = async () => {
    await setTimeout(() => {
      myform.value.reset();
    });
  };
</script>

<template>
  <div>
    <ElDialog
      :model-value="show"
      :title="title"
      :before-close="handleClose"
      :destroy-on-close="true"
    >
      <ElementForm
        ref="myform"
        :loadKey="formData.loadKey"
        :formFields="title == '新增' ? formData.formFields : formFieldset"
        :formRules="formData.formRules"
        :labelWidth="110"
        @update:value="hanldFromData"
      >
        <div style="text-align: center">
          <ElButton type="primary" :loading="loadingIcon" @click="getForm()">{{
            props.title == '新增' ? '提交' : '保存'
          }}</ElButton>
          <ElButton v-if="title == '新增'" @click="reset">重置表单</ElButton>
        </div>
      </ElementForm>
    </ElDialog>
  </div>
</template>

<style lang="scss" scoped></style>
